#include "receiverwidget.h"
#include "ui_receiverwidget.h"
#include <QUdpSocket>
ReceiverWidget::ReceiverWidget(QWidget *parent, const QString& devicename)
    : QWidget(parent)
    , ui(new Ui::ReceiverWidget)
    , name(devicename)
{
    ui->setupUi(this);
    init();

    qDebug() << "device name: " << name;
}

ReceiverWidget::~ReceiverWidget()
{
    SDL_Quit();
    delete ui;
}

void ReceiverWidget::init()
{
    this->setWindowTitle("Receiver");
    SDL_Init(SDL_INIT_VIDEO);

    // 设置TCP连接
    server.setParent(this);
    server.listen(QHostAddress::AnyIPv4, 8888); //tcp监听8888端口
    socket = nullptr;
    connect(&server, &QTcpServer::newConnection, this, &ReceiverWidget::newConnection);

    // 设置音频、视频解码器的接收缓冲区
    // 引用RTP接受者线程的接收缓冲区
    vDecoder.fifoBuffer = rtpRecv.fifoBufferVideo;
    aDecoder.fifoBuffer = rtpRecv.fifoBufferAudio;

    // 让RTP接受者线程跑起来
    rtpRecv.setRunState(true);

    udpSocket = new QUdpSocket(this);
}

void ReceiverWidget::newConnection() //当tcp server有新连接进来时，调用该函数
{
    if(socket != nullptr)
        socket->abort();

    socket = server.nextPendingConnection(); //获取这个新连接的套接字
    connect(socket, &QTcpSocket::readyRead, this, &ReceiverWidget::recvTcpData);
}

void ReceiverWidget::recvTcpData() //当socket有数据可读时，调用该函数
{
    QByteArray array = socket->readAll();
    qDebug() << "Recevie TCP data from Sender.";
    RTPMediaInfo *info = (RTPMediaInfo *)array.data();

    if(info->length != array.size())
    {
        qDebug() << "RTPMediaInfo->length not right.";
        return;
    }

    if(info->cmd == 1) //开始传输
    {
        qDebug() << "Start Real Time Communication.";

        QString s = socket->peerAddress().toString() + "正在向您共享屏幕";
        ui->label_state->setText(s);

        // 重设视频音频接收缓冲区
        rtpRecv.resetRecvBuffer();

        // 设置音频解码器
        if(info->hasAudio)
        {
            aDecoder.initDecodeParm(info->sampleRate, info->format, info->channel);
            aDecoder.setRunState(true);
            qDebug() << "init audio decode parameter: " << info->sampleRate << info->format << info->channel;
        }
        // 设置视频解码器
        if(info->hasVideo)
        {
            vDecoder.initDecodeParm((void *)ui->show->winId(), info->width, info->height);
            vDecoder.setRunState(true);
            qDebug() << "init video decode parameter: " << info->width << info->height;
        }
    }
    else if(info->cmd == 2) //结束传输
    {
        qDebug() << "Stop Real Time Communication.";
        ui->label_state->setText("waiting...");
        vDecoder.setRunState(false);
        aDecoder.setRunState(false);
    }
}

void ReceiverWidget::on_pushButton_clicked()
{
    // 向局域网发送UDP包，包内的内容是当前昵称
    QByteArray data = name.toUtf8();

    // 广播地址和端口
    QHostAddress broadcastAddress = QHostAddress::Broadcast;
    quint16 targetPort = 8557;

    if (udpSocket->writeDatagram(data, broadcastAddress, targetPort) == -1) {
        qDebug() << "Failed to send datagram:" << udpSocket->errorString();
    } else {
        qDebug() << "Datagram sent to broadcast address";
    }
}

